package leetcode_2001_2100;

import java.util.*;

public class LeeCode_2054 {
    public static void main(String[] args) {
        System.out.println(maxTwoEvents2(new int[][]{{1, 3, 2}, {4, 5, 2}, {2, 4, 3}}));
    }
    private static int maxTwoEvents2(int[][] events) {
        int n = events.length;
        Arrays.sort(events, (o1, o2) -> {
            if (o1[0] == o2[0]) {
                return o1[2] - o2[2];
            }
            return o1[0] - o2[0];
        });
        int[][] copy = new int[n][2];
        for (int i = 0; i < n; i++) {
            copy[i] = events[i].clone();
        }
        int max = 0;
        for (int i = n - 1; i >= 0; i--){
            max = Math.max(max, events[i][2]);
            events[i][2] = max;
        }
        int ans = 0;
        for (int i = 0; i < events.length; i++) {
            int val = copy[i][2], end = events[i][1];
            int index = bigger(events, end);
            if (index != -1) {
                val += events[index][2];
            }
            ans = Math.max(ans, val);
        }
        return ans;
    }
    private static int bigger(int[][] events, int goal){
        int n = events.length, l = 0, r = n - 1;
        while (l < r){
            int m = (l + r) / 2;
            if (events[m][0] <= goal){
                l = m + 1;
            }else {
                r = m;
            }
        }
        if (events[l][0] <= goal)
            return -1;
        return l;
    }
    private static int maxTwoEvents(int[][] events) {
        TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>();
        for (int[] event : events) {
            if (map.containsKey(event[0])){
                map.get(event[0]).add(event[2]);
            }else {
                TreeSet<Integer> set = new TreeSet<>();
                set.add(event[2]);
                map.put(event[0], set);
            }
        }
        List<Integer> list = new ArrayList<>(map.keySet());
        int len = list.size();
        int max = 0;
        for(int i = len - 1; i >= 0; i--){
            int key = list.get(i);
            max = Math.max(max, map.get(key).last());
            map.get(key).add(max);
        }

        int ans = 0;
        for (int[] event : events) {
            int val = event[2];
            ans = Math.max(val, ans);
            int end = event[1];
            Integer next = map.higherKey(end);
            if (next != null){
                ans = Math.max(ans, map.get(next).last() + val);
            }
        }
        return ans;
    }
}